import { getsn, getYYYYMM, getFileYYYYMMDDHH24MISS } from "@/utils/getsn"
import { downSecurityProject } from "@/utils/serviceUtils"
export function CallNet(url, code, param, successCall, errorCall) {
  console.log(JSON.stringify(param));
  AndroidApi.callNet({
    "type": "post",
    "param": {
      "url": url || "/open/buzadapter/access/commonInvoke",
      "code": code || "restApp",
      "inputParams": param
    }
  },
    function (success) {
      console.log(param);
      console.log(success);
      // console.log(success)
      if (success.resultCode === '9999') {
        try {
          // console.log(success.result)
          // console.log(typeof success.result)
          success.result = JSON.parse(success.result)
        } catch (e) {
          console.log(e);
          // console.log("JSON转换失败：");
          // console.log(success.result);
          //              errorCall("JSON转换失败："+success.result);
          errorCall(e);
        }
        if (success.result.CODE === '0') {
          successCall(success);
        } else {
          // console.log(success.result.CODE);
          errorCall("错误代码：" + success.result.CODE + ",错误信息：" + success.result.DESC);
        }

      }
    },
    function (error) {
      console.log(error);
      errorCall(error);
    })
}
let UserInfo = AndroidApi.getUserInfo();

let ServiceCode = {
  "SecurityProject": "RSC014",//安检项目
  "UserInfo": "RCS011",//用户信息下载
  "UserAccount": "RCS012",//用户账户信息
  "HistorySecurity": "RSC015",//历史安检下载
  "SecurityList": "RSC011",//安检任务列表
  "pCode": "RPB042",//标准代码下载
  "paramInfo": "RPB039",//配置信息下载
  "packgeList": "RMD020",//套餐信息下载
  "Charge": "RCA003",//收费信息上传
  "TransactTask": "RPB025",//单任务下载
  "TransactStop": "RCS042",//报停明细
  "TeansactStopUp": "RCS043",//报停明细上传
  "TransactOpen": "RCS029",//开栓明细
  "TransactStart": "RCS045",//启封明细
  "TransactChange": "RCS036",//改线明细
}
let PhotoType = {
  "securityProjectDtl": "010101",//安检项目明细拍照的ITEN_NO，BUSY_NO对应CODE_VAL
  "userSign": "010201",//客户签名图片类型的ITEM_NO无BUSY_NO
}
let GetParam = function (paramName, mWindow) {
  let paramValue = "",
    isFound = !1;
  if (mWindow.location.search.indexOf("?") == 0 && mWindow.location.search.indexOf("=") > 1) {
    let arrSource = unescape(mWindow.location.search).substring(1, mWindow.location.search.length).split("&"),
      i = 0;
    while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
  }
  return paramValue == "" && (paramValue = null), paramValue
}

export {
  UserInfo,
  PhotoType,
  GetParam,
  ServiceCode,
};

export function initApi() {
  // console.log("api start");
  (function (b) { console.log("AndroidApi initialization begin"); var a = { queue: [], callback: function () { var d = Array.prototype.slice.call(arguments, 0); var c = d.shift(); var e = d.shift(); this.queue[c].apply(this, d); if (!e) { delete this.queue[c] } } }; a.alert = a.back = a.callNet = a.changeImg2Base64 = a.checkTableExist = a.decode = a.deletes = a.encode = a.gotoHome = a.initCreateTables = a.insert = a.queryAllTableName = a.queryTableData = a.scanCode = a.takePhoto = a.toast = a.toast = a.update = function () { var f = Array.prototype.slice.call(arguments, 0); if (f.length < 1) { throw "AndroidApi call error, message:miss method name" } var e = []; for (var h = 1; h < f.length; h++) { var c = f[h]; var j = typeof c; e[e.length] = j; if (j == "function") { var d = a.queue.length; a.queue[d] = c; f[h] = d } } var g = JSON.parse(prompt(JSON.stringify({ method: f.shift(), types: e, args: f }))); if (g.code != 200) { throw "AndroidApi call error, code:" + g.code + ", message:" + g.result } return g.result }; Object.getOwnPropertyNames(a).forEach(function (d) { var c = a[d]; if (typeof c === "function" && d !== "callback") { a[d] = function () { return c.apply(a, [d].concat(Array.prototype.slice.call(arguments, 0))) } } }); b.AndroidApi = a; console.log("AndroidApi initialization end"); var evt = document.createEvent("HTMLEvents"); evt.initEvent("apiready", false, false); document.dispatchEvent(evt); })(window);
  // console.log("api end");
}

/**
 * 拍照公用功能
 * @param {*} app_no 工单编号 ""
 * @param {*} cons_no 用户编号
 * @param {*} item_no 照片类型 1202 联系信息 1203 合同信息 1204 开票信息
 * @param {*} busy_no 业务编码 0
 * @param {*} successCall 成功回调
 * @param {*} errorCall 失败回调
 */
export function takePhoto(app_no, cons_no, item_no, busy_no, successCall, errorCall) {
  //APP_NO VARCHAR2(16),CONS_NO VARCHAR2(16), FILE_SRC VARCHAR2(128), e2(256), ITEM_NO VARCHAR2(16), BUSY_NO VARCHAR2(16) 
  var takePhoto = {
    "photoType": "ALL",
    "quality": "50"
  };
  console.log("拍照入参" + JSON.stringify(takePhoto))
  AndroidApi.takePhoto(takePhoto, function (photoMsg) {
    console.log(photoMsg);
    var fileName = "/IMG/" + getYYYYMM() +
      "/" + app_no +
      "_" + cons_no +
      "_" + item_no +
      "_" + getFileYYYYMMDDHH24MISS();
    let fileId = new Date().getTime() + "";
    AndroidApi.insert(JSON.stringify({
      "tableName": "FILE_RECORDE",
      "contentValues": [{
        "FILE_ID": fileId,
        "APP_NO": app_no,
        "CONS_NO": cons_no,
        "FILE_SRC": photoMsg.path,
        "FILE_NAME": fileName,
        "ITEM_NO": item_no,
        "BUSY_NO": busy_no,
      }]
    }), function (msg) {
      if (msg.resultCode === '9999') {
        photoMsg.fileId = fileId;
        successCall(photoMsg);
      } else {
        errorCall(msg.resultMsg);
      }

    });
  });
}
/**
 * 获取图片list
 * @param {*} tArray 需要添加图片list的Object，该Object.BUSY_NO根据对应图片添加
 * @param {*} app_no 工单号
 * @param {*} cons_no 用户号
 * @param {*} photoType 图片类型
 * @param {*} successCall 
 */
export function getPhotoList(tArray, app_no, cons_no, photoType, successCall) {
  let count = 1;
  console.log(tArray.length)
  let width = window.screen.width;
  let height = window.screen.height;
  tArray.forEach(function (elment, index) {
    let photoListParam = {
      "whereClause": "SELECT a.*,a.FILE_SRC src  FROM FILE_RECORDE a WHERE a.APP_NO = ? and a.CONS_NO = ? and a.ITEM_NO = ? and a.BUSY_NO = ?",
      "whereArgs": [app_no, cons_no, photoType, elment.BUSY_NO]
    }
    // console.log("photoListParam"+JSON.stringify(photoListParam));
    AndroidApi.queryTableData(JSON.stringify(photoListParam), function (msg) {
      // msg.result.forEach(function(mMsg){
      // 	mMsg.src = "";
      // });
      console.log("photoList" + JSON.stringify(msg));
      if (msg.resultCode === '9999') {
        elment.photoList = msg.result;
      }
      console.log(count);
      if (count === tArray.length) {
        // console.log("tArray"+JSON.stringify(tArray))
        successCall(tArray);
      } else {
        count++;
      }
    });
  });
}
/**
 * 删除图片
 * @param {*} photoName 图片名称
 * @param {*} successCall 成功回调函数string
 */
export function deletePhoto(photoSrc, successCall) {
  let delPhoto = {
    "tableName": "FILE_RECORDE",
    "whereClause": "FILE_SRC=?",
    "whereArgs": [photoSrc]
  }
  console.log("delPhoto" + JSON.stringify(delPhoto))
  AndroidApi.deletes(JSON.stringify(delPhoto), function (msg) {
    console.log("SC_RST_DTL_Table删除记录:" + JSON.stringify(msg))
    // AndroidApi.alert(JSON.stringify(msg));
    successCall("删除图片成功！");
  });
}







/**
 * 复制接口文档字段内容，和表明，调用此方法生成建表语句
 * @param {String}} doc 复制文档的字段代码，字段名称，数据类型三列，拼成字符串
 * 例如以下格式：
 * "CONT_ID	实体的唯一标识	NUMBER(16)"+
 * "CONS_ID	用户标识	NUMBER(16)"
 * @param {String} tableName 表名称
 */
function getCreateSql(doc, tableName) {
  let sql = "CREATE TABLE IF NOT EXISTS " + tableName + "(";
  let column = [];
  doc.split(" ").forEach(function (element) {
    element && column.push(element);
  })
  column.forEach(function (element) {
    let tmp = element.split("	");
    tmp[2] === 'DATE' && tmp[2] == 'VARCHAR2(32)'
    sql = sql + tmp[0] + " " + tmp[2] + ","
  });
  sql = sql.substring(0, sql.length - 1) + ")";
  return sql;
}

